<?php

/**
 * This is the model class for table "role".
 *
 * The followings are the available columns in table 'role':
 * @property integer $id
 * @property string $name
 * @property string $remark
 *
 * The followings are the available model relations:
 * @property Menu[] $menus
 * @property Permission[] $permissions
 * @property User[] $users
 */
class Role extends CActiveRecord
{
    public $searchKey = '';

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'role';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name', 'required'),
            array('name', 'unique'),
            array('name', 'length', 'max' => 32),
            array('remark', 'length', 'max' => 1024),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, name, remark, searchKey', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'users' => array(self::HAS_MANY, 'User', 'rid'),
            'menus' => array(self::MANY_MANY, 'Menu', 'role_menu(rid, mid)'),
            'auths' => array(self::MANY_MANY, 'Auth', 'role_auth(rid, aid)'),
            'permissions' => array(self::MANY_MANY, 'Permission', 'role_permission(rid, pid)'),
            'menu_permissions' => array(self::MANY_MANY, 'Permission', 'role_permission(rid, pid)', 'condition' => 'type = ' . Permission::TYPE_MENU),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => '名称',
            'remark' => '备注',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('remark', $this->remark, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }


    public function searchByKey()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $criteria = new CDbCriteria;
        //屏蔽admin
        if ($this->searchKey !== '') {
            $criteria->addSearchCondition('name', $this->searchKey, true, 'OR');
            $criteria->addSearchCondition('remark', $this->searchKey, true, 'OR');
        }
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function isAdmin()
    {
        if (isset($this->id) && ($this->id !== '')) {
            return ($this->id == Yii::app()->params['admin_rid']);
        }
        return false;
    }

    public function getPermitArray()
    {
        $permitArray = array();
        if (isset($this->id) && ($this->id !== '')) {
            if ($this->isAdmin()) {
                $permissions = Permission::model()->findAll('authtype != :authtype', array(':authtype' => Permission::AUTHTYPE_FREE));
                foreach ($permissions as $permission) {
                    $permitArray[$permission->id] = $permission->id;
                }
            } else {
                $rps = RolePermission::model()->findAll('rid = :rid', array('rid' => $this->id));
                foreach ($rps as $rp) {
                    $permitArray[$rp->pid] = $rp->pid;
                }
                $adminActions = CHtml::listData(Permission::model()->findAll('authtype = :authtype', array(':authtype' => Permission::AUTHTYPE_ADMIN)), 'id', 'action');
                foreach ($adminActions as $p_id => $p_action) {
                    if (isset($permitArray[$p_id])) {
                        unset($permitArray[$p_id]);
                    }
                }
            }

        }
        return $permitArray;
    }

    public function getAuthArray($type = Auth::TYPE_API)
    {
        $authArray = array();
        $auths = $this->getAuths($type);
        foreach ($auths as $auth) {
            $authArray[$auth->id] = $auth->id;
        }
        return $authArray;
    }

    public function getAuths($type = Auth::TYPE_API)
    {
        $auths = array();
        if (!empty($this->id)) {
            if ($this->isAdmin()) {
                $auths = Auth::model()->findAll();
            } else {
                $auths = $this->auths;
            }
        }
        //filter the auth with the need type
        $auths = array_filter($auths,function($auth ,$key)use($type){
            if(!empty($auth))
            {
                return $auth->type == $type;
            }
            return true;
        },ARRAY_FILTER_USE_BOTH);
        return $auths;
    }

    public function getMenuArray()
    {
        $menuArray = array();
        if (isset($this->id) && ($this->id !== '')) {
            if ($this->isAdmin()) {
                $menus = Menu::model()->findAll('auth = :auth', array(':auth' => Menu::AUTH_LOGIN));
                foreach ($menus as $menu) {
                    $menuArray[$menu->id] = $menu->id;
                }
            } else {
                $rms = RoleMenu::model()->findAll('rid = :rid', array(':rid' => $this->id));
                foreach ($rms as $rm) {
                    $menuArray[$rm->mid] = $rm->mid;
                }
            }
        }
        return $menuArray;
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Role the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }
}
